<?php

class Model_User extends Joob_Db_Table	{
	
	protected $key = "id";
	
	protected $db = "users";
	
	## AUTHENTICATION FUNCTIONS
	
	public function login() {
		$email = $this->email;
		$password = $this->pwd;
		
		$errors = array();
		
		if (! Joob_Utils_Validator::email($email)) {
			$errors = "Email không hợp lệ.";
			return $errors; 
		}
		
		if (! Joob_Utils_Validator::password($password)) {
			$errors = "Password không hợp lệ.";
			return $errors;
		}
		
		$rows = $this->search("email='$email' " , 'id, pwd', 1);
		
		if (count($rows) != 1 || $rows[0]->pwd!=sha1($password)) {
			$errors = "Email hoặc password không hợp lệ.";
			return $errors;
		} else {
			$this->extend($rows [0]);
			return true;
		}
	}
	
	public function updateAccount()	{
		return $this->edit('email, pwd');
	}
	
	public function lostPassword(){
		$this->pwd=Joob_Utils_Word::random(13);
		$this->edit('pwd');
			
		$sender='daisy@daisy.com';
		$subject=' Tạo mật khẩu mới!';
		$content=' Mật khẩu mới: '.$this->pwd.'
					
						Ban quản trị <a href="http://daisy.com/">Daisy</a>';
		$headers=" MIME-Version: 1.0 \n\r";
		$headers.="Content-type:text/html;charset=UTF-8 \r\n";
		$headers.="From <".$sender.">\r\n";

		if(!mail($this->email, $subject, $content, $headers))
			throw new Exception("Tạo mật khẩu mới thất bại.");
		else
			return true;
	}
	
	public function getInfo()	{
		$user = $this;
		return array('email'=>$user->email, 
					'full_name'=>$user->full_name 
		);
	}
}

?>